package com.fhz.kotlintest.databinding.fragment

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fhz.kotlintest.Data
import com.fhz.kotlintest.databinding.repository.FoodRepository
import com.fhz.kotlintest.databinding.utils.LoadState
import kotlinx.coroutines.launch
import java.lang.Exception

class FoodViewModel : ViewModel() {

    //数据状态
    val loadState by lazy {
        MutableLiveData<LoadState>()
    }

    val contentList by lazy {
        MutableLiveData<MutableList<Data>>()
    }

    //仓库
    private val foodRepository by lazy {
        FoodRepository()
    }

    companion object{
        const val DEFAULT_PAGE = 1
    }

    private var mCurrentPage = DEFAULT_PAGE

    fun loadData(){
        //加载ui层转圈(loading)
        //更新状态
        loadState.value = LoadState.LOADING
        //加载第一页数据
        loadDataByPage(mCurrentPage)

    }

    fun loadMoreData(){
        mCurrentPage++
        loadDataByPage(mCurrentPage)
    }
    //处理数据的几种情况
    private fun loadDataByPage(page:Int){

        try {
            //根据页码加载数据
            viewModelScope.launch {
                val foodByPage = foodRepository.getFoodByPage(page)

                if(foodByPage.data.isEmpty()){
                    loadState.value = LoadState.EMPTY
                }else{
                    //处理状态
                    loadState.value = LoadState.SUCCESS
                    //更新数据
                    var oldvalue = contentList.value?: mutableListOf()
                    oldvalue.addAll(foodByPage.data)
                    contentList.value = oldvalue
                }
            }
        }catch (e:Exception){
            loadState.value = LoadState.ERROE
        }

    }

}